package com.haredot.controller;

import com.haredot.entity.Organization;
import com.haredot.service.OrganizationService;
import com.haredot.utils.ValidUtils;
import com.haredot.vo.PageVo;
import com.haredot.vo.R;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/org")
public class OrganizationController {

    @Resource
    private OrganizationService organizationService ;

    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('org:add', 'org:add:child')")
    public R<?> addOrganization(@Validated @RequestBody Organization organization, BindingResult bindingResult) {

        return ValidUtils.toResult(bindingResult, ()-> organizationService.saveOrganization(organization));
    }

    @PutMapping("/update/{id}")
    @PreAuthorize("hasAuthority('org:update')")
    public R<?> updateOrganization(@PathVariable("id") Long id ,@RequestBody Organization organization, BindingResult bindingResult) {
        organization.setId(id);
        return ValidUtils.toResult(bindingResult, ()-> organizationService.updateOrganization(organization));
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('org')")
    public R<Organization> list() {
        return organizationService.queryOrganizationList();
    }


    @GetMapping("/{orgId}/users")
    @PreAuthorize("hasAuthority('org:query:user')")
    public R<PageVo> userList(@PathVariable("orgId") Long orgId,
                              @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
                              @RequestParam(value = "rows", required = false, defaultValue = "10") Integer rows) {

        PageVo pageVo = new PageVo(page, rows) ;

        return organizationService.queryUserList(pageVo, orgId);
    }


    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAuthority('org:delete')")
    public R<?> deleteOrg(@PathVariable Long id) {

        return organizationService.removeOrg(id);
    }
}
